module.exports = class extends think.Controller {
  async __before() {
    // 登录验证
    const is_login = await this.islogin();
    console.log(is_login)
    if (!is_login) {
      return this.redirect('/admin/public/signin');
    }
    this.user = await this.session('userInfo');
    this.assign('userinfo', this.user);
    this.roleid = await this.model('auth_user_role').where({user_id: this.user.uid}).getField('role_id', true);
    this.is_admin = await this.is_admin();
    // 后台菜单
    this.adminmenu = await this.model('kms/menu').getallmenu(this.user.uid, this.is_admin);
    const url = `${this.ctx.controller}/${this.ctx.action}`;
    if (!this.is_admin) {
      const auth = this.service('kms/rbac', this.user.uid);
      const res = await auth.check(url);
      if (!res) {
        const error = this.controller('kms/error');
        return error.noAction('未授权访问!');
      }
    }
  }
  /**
   * 判断是否登录
   * @return {boolean}
   */
  async islogin() {
    const user = await this.session('webuser');
    const res = think.isEmpty(user) ? false : user.uid;
    return res;
  }
  async weblogin() {
    const islogin = await this.islogin();
    if (!islogin) {
      // 判断浏览器客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录界面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/kms/error/login');
      }
    }
  }
  // 跨域设置
  setCorsHeader() {
    this.header('Access-Control-Allow-Origin', this.header('origin') || '*');
    this.header('Access-Control-Allow-Headers', 'x-requested-with');
    this.header('Access-Control-Request-Method', 'GET,POST,PUT,DELETE');
    this.header('Access-Control-Allow-Credentials', 'true');
  }
}
